import datetime

from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

from finance.api.utils import create_journal, get_account, remove_journal
from points.models import Recharge


# 资金账单保存

@receiver(post_save, sender=Recharge)
def handle_recharge_journal(sender, instance, created, **kwargs):
    print('handle_recharge_journal')

    if instance.category == 0:      # 费用
        source = '客户充值'

        account = get_account(instance.account_id)

        data = {
            'order_no': instance.code,
            'name': instance.customer.name,
            'order_time': datetime.datetime.now(),
            'account': instance.account or None,
            'source': source,
            'money': instance.money,
            'balance': account.balance,
            'user': instance.user or None,
            'desc': instance.remark,
            'created': created,
        }
        print(data)
        # 流水账记录
        create_journal(**data)


# 充值删除
@receiver(post_delete, sender=Recharge)
def handle_recharge_remove_journal(sender, instance, **kwargs):
    print('handle_recharge_remove_journal')
    # 更新账户余额
    remove_journal(instance.code)


